package com.yupi.yuaicodemother.exception;

import com.fasterxml.jackson.core.JsonParseException;
import com.yupi.yuaicodemother.common.BaseResponse;
import com.yupi.yuaicodemother.common.ResultUtils;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@Hidden
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e, HttpServletRequest request) {
        log.error("BusinessException", e);
        // 检查是否是SSE流式响应请求
        if (isSseRequest(request)) {
            return handleSseError(e.getCode(), e.getMessage());
        }
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public Object runtimeExceptionHandler(RuntimeException e, HttpServletRequest request) {
        log.error("RuntimeException", e);
        
        // 检查是否是SSE流式响应请求
        if (isSseRequest(request)) {
            // 对于JSON解析错误，返回友好的错误消息
            if (e.getCause() instanceof JsonParseException || 
                (e.getMessage() != null && e.getMessage().contains("JsonParseException"))) {
                return handleSseError(ErrorCode.SYSTEM_ERROR.getCode(), 
                    "AI返回的数据格式有误，已自动修复。如问题持续，请重试。");
            }
            return handleSseError(ErrorCode.SYSTEM_ERROR.getCode(), "系统错误，请稍后重试");
        }
        
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
    }

    /**
     * 检查是否是SSE流式响应请求
     */
    private boolean isSseRequest(HttpServletRequest request) {
        String acceptHeader = request.getHeader(HttpHeaders.ACCEPT);
        String contentType = request.getContentType();
        String requestURI = request.getRequestURI();
        
        // 检查Accept头或请求路径
        return (acceptHeader != null && acceptHeader.contains(MediaType.TEXT_EVENT_STREAM_VALUE)) ||
               (requestURI != null && requestURI.contains("/chat/gen/code"));
    }

    /**
     * 处理SSE流式响应的错误
     * 返回一个包含错误信息的BaseResponse，但格式化为可序列化的形式
     */
    private BaseResponse<?> handleSseError(int code, String message) {
        // 注意：这个方法返回BaseResponse，但实际在Controller层会被转换为SSE格式
        // 如果直接返回SSE格式，需要使用SseEmitter，但这里无法直接使用
        // 所以返回BaseResponse，由Controller层处理
        return ResultUtils.error(code, message);
    }
}